from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from django.core.paginator import Paginator
from django.utils.timezone import utc
from cmdb import models
from cmdb import common
from cmdb import modules
import requests
import os
import datetime
import sys
from cmdb.modules import ReadExcel

# y有异常的站点
monitor_status = []


def index(request):
    if not request.session.get("user_id", None):
        return redirect("/users/login")
    menu = request.session["permission_menu_dict"]
    return render(request, "base.html", menu)


def web(request):
    if not request.session.get("user_id", None):
        return redirect("/users/login")
    return render(request, "web.html")


def webjson(request):
    data = list()
    page_index = request.GET.get("page", default=None)
    pageSize = request.GET.get("pageSize", default=None)
    for m in models.Web.objects.all():
        d = dict()
        d["id"] = m.id
        d["name"] = "<span style='color: red;font-weight:bold'>%s</span>" % (m.name)
        d["domain"] = "<a style='color: #0000FF;' href='http://%s' target='_blank'>%s</a>" % (m.domain, m.domain)
        d["nas"] = "<span style='color: #0000FF;'>%s</span>" % (m.namespace.nas)
        d["nas_catalogue"] = os.path.join(m.namespace.nas_catalogue, m.project, m.name)
        d["mysql_host"] = m.mysql_host
        d["namespace"] = m.namespace.name
        if m.php_status == 1:
            d["php_status"] = "<span style='color: green;font-weight:bold'>%s</span>" % ('正常')
        else:
            d["php_status"] = "<span style='color: red;font-weight:bold'>%s</span>" % ('异常')
        if m.status == 1:
            d["status"] = "<span style='color: green;font-weight:bold'>%s</span>" % ('正常')
        else:
            d["status"] = "<span style='color: red;font-weight:bold'>%s</span>" % ('异常')
        data.append(d)
    pageInator = Paginator(data, pageSize)
    contacts = pageInator.page(page_index)
    pagedata = [x for x in contacts]
    redata = {"code": 0, "msg": "", "count": len(data), "data": pagedata}
    return JsonResponse(redata, safe=False)


def searchjson(request):
    query = request.GET.get("query", default=None)
    data = list()
    for m in models.Web.objects.all():
        d = dict()
        d["id"] = m.id
        d["name"] = "<span style='color: red;font-weight:bold'>%s</span>" % (m.name)
        d["domain"] = "<a style='color: #0000FF;' href='http://%s' target='_blank'>%s</a>" % (m.domain, m.domain)
        d["nas"] = "<span style='color: #0000FF;'>%s</span>" % (m.namespace.nas)
        d["nas_catalogue"] = os.path.join(m.namespace.nas_catalogue, m.project, m.name)
        d["mysql_host"] = m.mysql_host
        if m.php_status == 1:
            d["php_status"] = "<span style='color: green;font-weight:bold'>%s</span>" % ('正常')
        else:
            d["php_status"] = "<span style='color: red;font-weight:bold'>%s</span>" % ('异常')

        d["namespace"] = m.namespace.name
        if m.status == 1:
            d["status"] = "<span style='color: green;font-weight:bold'>%s</span>" % ('正常')
        else:
            d["status"] = "<span style='color: red;font-weight:bold'>%s</span>" % ('异常')
        if query in str(d):
            data.append(d)
    redata = {"code": 0, "msg": "", "count": len(data), "data": data}
    return JsonResponse(redata, safe=False)


def webcheck(request):
    # 前端检测
    for u in models.Web.objects.all():
        url = "http://" + u.domain
        code = 0
        for i in range(2):
            s = requests.get(url, timeout=5)
            code = s.status_code
        if code == 200:
            if u.domain in monitor_status:
                monitor_status.remove(u.domain)
                print(common.dingding(url))
            print("OK {}网站访问正常".format(url))
            models.Web.objects.filter(id=u.id).update(status=1)
        else:
            models.Web.objects.filter(id=u.id).update(status=0)
            if u.domain not in monitor_status:
                print(u.domain)
                print(common.dingding(url, code))
                monitor_status.append(u.domain)

        if u.php_url:
            phpUrl = None
            if '/' in u.domain:
                phpUrl = "http://" + u.domain.split('/')[0] + u.php_url
            else:
                phpUrl = url + u.php_url
            print(phpUrl)
            code = 0
            s = requests.get(phpUrl, timeout=5)
            for i in range(2):
                code = s.status_code
            if code == 200:
                if u.php_url in monitor_status:
                    monitor_status.remove(u.php_url)
                    print(common.dingding(phpUrl))
                print("OK {}URL访问正常".format(phpUrl))
                models.Web.objects.filter(id=u.id).update(php_status=1)
            else:
                models.Web.objects.filter(id=u.id).update(php_status=0)
                if u.php_url not in monitor_status:
                    print("OK {}URL访问异常".format(phpUrl))
                    text=s.text
                    print(common.dingding(phpUrl,code,text))
                    monitor_status.append(u.php_url)
    return HttpResponse("ok")


def addweb(request):
    if request.method == "POST":
        data = request.body.decode()
        webdata = common.json_to_dict(data)
        web = modules.Web(webdata['project'], webdata['name'], webdata['domain'], webdata['namespace'])
        web.openresty_config()
        web.nas_pv_sm()
        web.openresty()
        web.php()
        web.ingress()
        clustername = models.Namespace.objects.get(name=webdata['namespace']).cluster.name
        res = modules.K8s(clustername)
        res.add_openresty_config(web.namespace, web.domain)
        print("openresty_config finished")
        res.add_www_pv_sm(web.namespace)
        print("www pv and sm finished")
        res.add_logs_pv_sm(web.namespace)
        print("logs pv and sm finished")
        res.add_openresty(web.namespace)
        print("openresty finished")
        res.add_php(web.namespace)
        print("php finished")
        res.add_openresty_svc(web.namespace)
        print("openresty-svc finished")
        res.add_php_svc(web.namespace)
        print("php-svc finished")
        res.add_ingress(web.namespace)
        print("ingress finished")
        w = dict()
        w["name"] = webdata['name']
        w['project'] = webdata["project"]
        w['domain'] = webdata["domain"]
        n = models.Namespace.objects.get(name=webdata["namespace"])
        w['namespace_id'] = n.id
        models.Web.objects.create(**w)
        redata = {"code": 200, "message": "保存成功！"}
        return JsonResponse(redata, safe=False)


def insertjob(request):
    if not request.session.get("user_id", None):
        return redirect("/users/login")
    clusters = models.Cluster.objects.all()
    for c in clusters:
        c_obj = modules.K8s(c.name)
        jobdata = c_obj.get_job()
        for j in jobdata[0]:
            d = dict()
            d["name"] = j
            d["cluster"] = c_obj.name
            d["status"]=1
            d['image']='registry-vpc.cn-shenzhen.aliyuncs.com/kbitweb/php7.2.16-cli:1.0.1'
            models.Dsjob.objects.create(**d)
    return HttpResponse("ok")

def jobcheck(request):
    clusters = models.Cluster.objects.all()
    for c in clusters:
        c_obj = modules.K8s(c.name)
        jobdata = c_obj.get_job()
        print(jobdata[1])
    return HttpResponse("ok")

def dsjob(request):
    if not request.session.get("user_id", None):
        return redirect("/users/login")
    return render(request, "dsjob.html")


def jobjson(request):
    data = list()
    page_index = request.GET.get("page", default=None)
    pageSize = request.GET.get("pageSize", default=None)
    for m in models.Dsjob.objects.all():
        d = dict()
        d["id"] = m.id
        d["name"] = "<span style='color: red;font-weight:bold'>%s</span>" % (m.name)
        d["image"] = "<a style='color: #0000FF;'>%s</a>" % (m.image)
        d["plan"] = "<span style='color: red;'>%s</span>" % (m.plan)
        d["cluster"] = "<span style='color: red;font-weight:bold'>%s</span>" % (m.cluster)
        d["create_time"] = m.create_time
        if m.status == 1:
            d["status"] = "<span style='color: green;font-weight:bold'>%s</span>" % ('正常')
        else:
            d["status"] = "<span style='color: red;font-weight:bold'>%s</span>" % ('异常')
        data.append(d)
    pageInator = Paginator(data, pageSize)
    contacts = pageInator.page(page_index)
    pagedata = [x for x in contacts]
    redata = {"code": 0, "msg": "", "count": len(data), "data": pagedata}
    return JsonResponse(redata, safe=False)

def searchjob(request):
    query = request.GET.get("query", default=None)
    data = list()
    for m in models.Dsjob.objects.all():
        d = dict()
        d["id"] = m.id
        d["name"] = "<span style='color: red;font-weight:bold'>%s</span>" % (m.name)
        d["image"] = "<a style='color: #0000FF;'>%s</a>" % (m.image)
        d["plan"] = "<span style='color: red;'>%s</span>" % (m.plan)
        d["cluster"] = "<span style='color: red;font-weight:bold'>%s</span>" % (m.cluster)
        d["create_time"] = m.create_time
        if m.status == 1:
            d["status"] = "<span style='color: green;font-weight:bold'>%s</span>" % ('正常')
        else:
            d["status"] = "<span style='color: red;font-weight:bold'>%s</span>" % ('异常')
        if query in str(d):
            data.append(d)
    redata = {"code": 0, "msg": "", "count": len(data), "data": data}
    return JsonResponse(redata, safe=False)

#服务器
def host(request):
    if not request.session.get("user_id", None):
        return redirect("/users/login")
    return render(request, "host.html")

def inserthost(request):
    if not request.session.get("user_id", None):
        return redirect("/users/login")
    r = ReadExcel('data/host.xlsm', 'ecs_instance_list_cn-shenzhen_2')
    data = r.read_data_line()
    for i in data:
        d = dict()
        d["name"] = i['名称']
        d["os"] = i['操作系统']
        d["status"]=i['状态']
        d["desc"]=i['描述']
        d["outip"]=None
        if i['弹性IP']:
            d["outip"]=i['弹性IP']
        elif i['公网IP']:
            d["outip"] = i['公网IP']
        d["inip"] = i['内网IP']
        d["cpu"] = i['CPU']
        d['mem'] = i['内存']/1024
        d['create_time'] = i['创建时间（UTC）']
        d['expiry_time'] = i['到期时间（UTC）']
        models.Host.objects.create(**d)
    return HttpResponse("ok")


def hostjson(request):
    data = list()
    page_index = request.GET.get("page", default=None)
    pageSize = request.GET.get("pageSize", default=None)
    host_list=list(models.Host.objects.all())
    host_list.reverse()
    for m in host_list:
        d = dict()
        d["name"] = "<span style='color: red;font-weight:bold'>%s</span>" % (m.name)
        d['os'] = m.os
        d['status'] = m.status
        d['desc'] = m.desc
        d['outip'] = m.outip
        d['inip'] = m.inip
        d['cpu'] = m.cpu
        d['mem'] = m.mem
        d['create_time'] = m.create_time
        day=(m.expiry_time-datetime.datetime.now().replace(tzinfo=utc)).days
        d['expiry_time']=m.expiry_time.strftime('%Y-%m-%d %H:%M:%S')
        if day>=0 and day<=7:
            d['expiry_time'] = "<span style='color: red;font-weight:bold'>%s</span>" % (m.expiry_time.strftime('%Y-%m-%d %H:%M:%S'))
        elif day<0:
            d['expiry_time'] = "<span style='color: red;font-weight:bold'>%s</span>" %("已过期")
        data.append(d)
    pageInator = Paginator(data, pageSize)
    contacts = pageInator.page(page_index)
    pagedata = [x for x in contacts]
    redata = {"code": 0, "msg": "", "count": len(data), "data": pagedata}
    return JsonResponse(redata, safe=False)